package com.hkd.service.impl;

import com.hkd.entity.OauthUser;
import com.hkd.user_service.api.SysUserService;
import com.hkd.user_service.api.vo.BaseUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HKD
 * @date 2022/8/21 20:49
 */
@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BaseUserInfo userInfo = sysUserService.getUserByAccount(username).getData();
        List<GrantedAuthority> grantedAuthorities=rolesToGrantedAuthority(userInfo.getRoleNames());
        if (userInfo!=null){
            User user = new User(userInfo.getAccount(),userInfo.getPassword(),
                    userInfo.getEnable(),true,true,
                    true, grantedAuthorities);
            return new OauthUser(userInfo,user);
        }else {
            throw new UsernameNotFoundException("不存在该用户");
        }
    }

    private List<GrantedAuthority> rolesToGrantedAuthority(List<String> roleNames) {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (String roleName : roleNames) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
            authorityList.add(authority);
        }
        return authorityList;
    }
}
